const express = require('express');
const router = express.Router();
const { auth, authorize } = require('../middleware/auth');
const { auditLogger, saveBefore } = require('../middleware/audit');
const validate = require('../middleware/validate');
const { paginate } = require('../middleware/pagination');
const userValidators = require('../validators/user');
const { User } = require('../models');
const userController = require('../controllers/userController');

// 仅 admin 可访问
router.use(auth, authorize('admin'));

// 列表（分页 + 状态/邮箱筛选）
router.get('/', paginate, userController.listUsers);

// 创建用户
router.post('/',
  validate(userValidators.createUser),
  auditLogger('create', 'user'),
  userController.createUser
);

// 更新用户（不含密码）
router.put('/:id',
  validate(userValidators.updateUser),
  saveBefore(User),
  auditLogger('update', 'user'),
  userController.updateUser
);

// 启用/禁用（可用 updateUser 统一处理，也提供专门接口）
router.put('/:id/status',
  validate(userValidators.updateStatus),
  saveBefore(User),
  auditLogger('update', 'user'),
  userController.updateStatus
);

// 重置密码（管理员指定新密码）
router.put('/:id/reset-password',
  validate(userValidators.resetPassword),
  saveBefore(User),
  auditLogger('update', 'user'),
  userController.resetPassword
);

// 删除用户
router.delete('/:id',
  saveBefore(User),
  auditLogger('delete', 'user'),
  userController.deleteUser
);

module.exports = router;


